package com.jiang.daily.Q1366;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jiang
 * @version 1.0
 * @date 2024/12/29 17:38
 */
class Solution {
    public String rankTeams(String[] votes) {
        Map<Character, int[]> map = new HashMap<>();
        // 对map集合赋值
        for (char c: votes[0].toCharArray()) {
            map.put(c, new int[votes[0].length()]);
        }

        // 统计
        for (String vote: votes) {
            for (int i = 0; i < vote.length(); i++) {
                ++map.get(vote.charAt(i))[i];
            }
        }

        // 取出键值对放入list集合中
        List<Map.Entry<Character, int[]>> list = new ArrayList<>(map.entrySet());

        // 排序
        list.sort((a, b) -> {
            for (int i = 0; i < a.getValue().length; i++) {
                if (a.getValue()[i] != b.getValue()[i]) {
                    return b.getValue()[i] - a.getValue()[i];
                }
            }
            return a.getKey() - b.getKey();
        });

        // 获取结果
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<Character, int[]> entry: list) {
            sb.append(entry.getKey());
        }

        return sb.toString();
    }
}
